package com.qing.utils;

import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 日期工具类
 * @author 竹秋廿四
 */
@Component
public class DateUtil {

    /**
     * 获取对应月份的工作日有多少天
     * @param str  格式：2022-06
     * @return {@link Integer }
     */
    public Integer getWorkDay(String str) {
        Calendar calendar = Calendar.getInstance(java.util.Locale.CHINA);
        String[] sp = str.split("-");
        calendar.set(Calendar.YEAR, Integer.parseInt(sp[0]));
        calendar.set(Calendar.MONTH, Integer.parseInt(sp[1]) - 1);
        //计算1号是星期几
        calendar.set(Calendar.DATE, 1);
        int countDay = getDay(sp[0], sp[1]);
        int workDay = 0;
        int countWeek = countDay / 7;
        int wd = calendar.get(Calendar.DAY_OF_WEEK);
        int yuDay = getYuTian(countDay % 7, wd);
        workDay = countWeek * 5 + yuDay;

        return workDay;
    }

    /**
     * 获取某月的总天数
     */
    public static int getDay(String year, String month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, Integer.parseInt(year));
        calendar.set(Calendar.MONTH, Integer.parseInt(month) - 1);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    public static int getYuTian(int endDay, int toDay) {
        int yuTian = 0;
        if (1 == toDay) {
            toDay += 5;
        } else {
            toDay = toDay - 2;
        }
        yuTian = endDay + toDay;
        if (yuTian > 7) {
            return yuTian % 7;
        }
        if (yuTian == 6) {
            return endDay - 1;
        } else if (yuTian == 7) {
            return endDay - 2;
        } else {
            return endDay;
        }
    }

}